package top.fangw.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.fangw.admin.pojo.entity.SysUser;
import top.fangw.admin.mapper.SysUserMapper;
import top.fangw.admin.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.fangw.common.api.vo.InitAdminUserVo;
import top.fangw.common.api.vo.UserVo;
import top.fangw.common.core.exception.BizException;
import top.fangw.common.mybatis.annotation.DyDataSource;
import top.fangw.common.mybatis.util.TenantHelper;

/**
 * <p>
 * 用途：存储用户信息 服务实现类
 * </p>
 *
 * @author fangw
 * @since 2024-02-21
 */
@Service
@DS("base_info")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    @DyDataSource(tenantId = "#sysUser.tenantId")
    public void add(SysUser sysUser) {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        // 加密用户密码
        sysUser.setPassword(encoder.encode(sysUser.getPassword()));
        this.baseMapper.insert(sysUser);
    }

    @Override
    @DyDataSource
    public UserVo selectByUsername(String username) {
        UserVo userVo = this.baseMapper.selectByUsername(username);
        return null;
    }

    @Override
    @DyDataSource(tenantId = "#tenantId")
    public UserVo selectByUsernameAndTenantId(String username, String tenantId) {
        UserVo userVo;
        if (TenantHelper.get() != null && !((Boolean) TenantHelper.get())) {
            userVo = this.baseMapper.selectByUsernameAndTenantId(username, tenantId);
        } else {
            userVo = this.baseMapper.selectByUsername(username);
        }
        return userVo;
    }

    @Override
    @DyDataSource(tenantId = "#initAdminUserVo.tenantId",autoTenantId = false)
    public InitAdminUserVo initTenantAdminUser(InitAdminUserVo initAdminUserVo) {
        UserVo userVo = selectByUsernameAndTenantId(initAdminUserVo.getLoginName(), initAdminUserVo.getTenantId());
        if(userVo!=null){
            throw new BizException("该租户下当前用户已经存在！");
        }
        SysUser sysUser = BeanUtil.copyProperties(initAdminUserVo, SysUser.class);
        this.baseMapper.insert(sysUser);
        return BeanUtil.copyProperties(sysUser,InitAdminUserVo.class);
    }
}
